<template>
  <section class="login-container">
    <section class="login-bg">
      <el-image :src="obj.bgsrc" fit="cover">
        <div slot="error" class="image-slot">
          <img src="../images/login-bg.png">
        </div>
      </el-image>
    </section>

    <section class="login-inner">
      <section class="inner-logo">
        <el-image :src="obj.logosrc">
          <div slot="error" class="image-slot">
            <img src="../images/login-logo.png">
          </div>
        </el-image>
      </section>

      <section class="inner-title">
        <template v-if="obj.name">{{ obj.name || "" }}</template>
      </section>

      <section class="inner-form">
        <el-form v-show="!forget && !SMScode" ref="form" :model="form" :rules="rules" class="login-form" auto-complete="on" label-position="left" label-width="30px">
          <el-form-item prop="phoneNumber" label>
            <el-input v-model.trim="form.phoneNumber" auto-complete="on" name="phoneNumber" type="text" placeholder="请输入您的手机号码">
              <i slot="prefix" class="el-icon-user-solid" />
            </el-input>
          </el-form-item>
          <el-form-item label>
            <el-input v-model.trim="form.password" :type="pwdType" name="password" placeholder="请输入密码">
              <i slot="prefix" class="el-icon-lock" />
            </el-input>
            <span class="show-pwd" @click="pwdType = pwdType === 'password' ? '' : 'password'">
              <svg-icon v-if="pwdType == 'password'" icon-class="eye" />
              <i v-else class="el-icon-view" />
            </span>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%; height:44px; margin-top: 20px;border-radius:20px;" @click.native.prevent="handleLogin" @keyup.enter.native="handleLogin">登 录</el-button>
          <section class="clearfix">
            <p class="forget-password fr" @click="SMScode = true">短信登录</p>
            <p class="forget-password fl" @click="forget = true">忘记密码？</p>

          </section>
        </el-form>

        <!-- 短信验证码登录↓ -->
        <el-form
          v-show="SMScode"
          ref="SMScodeForm"
          :model="SMScodeForm"
          :rules="SMScodeRules"
          class="login-form forget"
          auto-complete="on"
          label-position="left"
          label-width="70px"
        >
          <!-- <div class="title-container">短信登录</div> -->
          <el-form-item prop="phoneNumber" label="手机号码:">
            <el-input
              v-model.trim="SMScodeForm.phoneNumber"
              auto-complete="on"
              name="phoneNumber"
              type="text"
              placeholder="请输入您的手机号码"
            />
          </el-form-item>

          <el-form-item prop="msgCode" label="验证码:">
            <el-input
              v-model.trim="SMScodeForm.smsCode"
              style="width: 50%"
              auto-complete="on"
              name="code"
              placeholder="请输入验证码"
            />
            <el-button
              type="success"
              :disabled="(disabled = !showLogin)"
              class="send-code-btn"
              @click="sendCodeLogin"
            >
              <span v-show="showLogin">获取验证码</span>
              <span
                v-show="!showLogin"
                class="count"
              >{{ countLogin }}s后重新获取</span>
            </el-button>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-top: 20px; border-radius: 20px"
            @click.native.prevent="SMShandleLogin"
          >登录</el-button>
          <p
            class="forget-password"
            @click="
              forget = false;
              SMScode = false;
            "
          >
            账号密码登录
          </p>
        </el-form>
        <!-- 短信验证码登录↑ -->
      </section>
      <!-- <div class="inner-bottom" /> -->
    </section>

    <!-- 找回密码 -->
    <section v-if="forget" class="login-forget">
      <Forget @closeforget="forget = false" />
    </section>

    <!-- 超级管理员初始密码 -->
    <section v-if="set" class="login-set">
      <Set @closeset="set = false" />
    </section>

    <section class="login-bottom">
      <template v-if="pageFooter.length>0">
        <span v-for="(item,index) in pageFooter" :key="index">{{item.value}}&nbsp;&nbsp;&nbsp;&nbsp;</span>
      </template>
      <template v-else>
        主办单位 ：中华全国总工会&nbsp;&nbsp;&nbsp;&nbsp;技术支持：中慧智工新媒体科技有限公司&nbsp;&nbsp;&nbsp;&nbsp;
        内容支持：《中国工人》杂志社
      </template>
    </section>
  </section>
</template>
<script>
import Forget from '../components/forget'
import Set from '../components/set'
import { getDataByType, getPhoneCode } from '../api/login'
import { phone } from '@/utils/validate'
import { exportSign } from '@/utils/fileImportOrExportSign'
import store from '@/store'
const TIME_COUNT = 60 // 更改倒计时时间
export default {
  name: 'Login',
  components: { Forget, Set },
  data() {
    return {
      pageFooter:[],
      form: {
        phoneNumber: '',
        password: '',
        code: '',
        type: 1
      },
      rules: {
        phoneNumber: [{ trigger: 'blur', validator: phone }],
        password: [{
          trigger: 'blur', validator: (rule, value, callback) => {
            const reg = /^(?!.*\s)(?!^[\u4e00-\u9fa5]+$)(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{8,30}$/
            if (!value) {
              callback(new Error('请输入新密码'))
            } else if (!reg.test(value)) {
              callback(new Error('密码长度必须大于等于8位小于等于30位。必须包含大写字母、小写字母、数字、特殊字符中的3种。'))
            } else {
              callback()
            }
          }
        }]
      },
      pwdType: 'password',
      SMScode: false, // 短信验证码登录code
      SMScodeForm: {
        // 短信验证码登录
        phoneNumber: '',
        smsCode: ''
      },
      SMScodeRules: {
        phoneNumber: [{ trigger: 'blur', validator: phone }],
        code: [{ message: '请输入验证码', trigger: 'blur' }]
      },
      loading: false,
      redirect: undefined,
      forget: false,
      set: false,
      obj: {
        bgsrc: '/API-ENTERPRISE-BACKEND/backend/sys/sysConfig/fileDownloadByName' + exportSign({ name: 'BACKEND_BACKGROUND_IMG' }).paramStr,
        logosrc: '/API-ENTERPRISE-BACKEND/backend/sys/sysConfig/fileDownloadByName' + exportSign({ name: 'BACKEND_LOGIN_LOGO' }).paramStr,
        name: ''
      },
      showLogin: true, // 初始发送验证码启用按钮 --- 短信验证码登录
      countLogin: '', // 初始化发送验证次数 --- 短信验证码登录
      timerLogin: null, // 发送验证码倒计时 --- 短信验证码登录

      showMailBox: true, // 初始发送验证码启用按钮 --- 邮箱找回密码
      countMailBox: '', // 初始化发送验证次数 --- 短信验证码登录
      timerMailBox: null // 发送验证码倒计时 --- 短信验证码登录
    }
  },
  watch: {
    $route: {
      handler(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.$store.dispatch('delAllCachedViews') // 将所有的缓存页面清空
    this.getSystemName()
    this.getPageFooter()
    window.addEventListener('keyup', this.enterLogin)
  },
  destroyed() {
    window.removeEventListener('keyup', this.enterLogin)
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('LoginByPhoneAndPwd', this.form).then(() => {
            this.loading = false
            localStorage.setItem('isLogin', 1)
            this.$router.push({ path: '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /** 短信验证码登录 */
    SMShandleLogin() {
      this.$refs.SMScodeForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('LoginByPhone', this.SMScodeForm)
            .then(() => {
              this.loading = false
              localStorage.setItem('isLogin', 1)
              this.$router.push({ path: '/' })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    enterLogin(e) {
      if (e.keyCode === 13 && !this.forget) {
        this.handleLogin()
      }
    },
    /**
     * 短信验证码登录获取验证码
     */
    sendCodeLogin() {
      // const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
      const reg = /^1\d{10}$/
      if (this.SMScodeForm.phoneNumber === '') {
        this.$message({
          message: '请输入手机号码！',
          type: 'warning'
        })
        return
      } else if (!reg.test(this.SMScodeForm.phoneNumber)) {
        this.$message({
          message: '请输入正确的11位手机号码！',
          type: 'warning'
        })
        return
      }
      if (!this.timer) {
        this.countLogin = TIME_COUNT
        this.showLogin = false
        return new Promise((resolve, reject) => {
          this.timerLogin = setInterval(() => {
            if (this.countLogin > 0 && this.countLogin <= TIME_COUNT) {
              this.countLogin--
            } else {
              this.showLogin = true
              clearInterval(this.timerLogin) // 清除定时器
              this.timerLogin = null
            }
          }, 1000)
          getPhoneCode({ phoneNumber: this.SMScodeForm.phoneNumber, smsType: '4' })
            .then(res => {
              this.$message({
                message: '短信已发送，请注意查收！',
                type: 'success'
              })
            })
            .catch(error => {
              reject(error)
              this.showLogin = true
              this.timerLogin = null
            })
        })
      }
    },
    getSystemName() {
      return new Promise((resolve, reject) => {
        getDataByType({ name: 'PAGE_TOP_TITLE' }).then((res) => {
          this.obj.name = res.data.data.configValue || '数字化工会管理系统'
        }).catch(error => {
          reject(error)
        })
      })
    },
    getPageFooter() {
      return new Promise((resolve, reject) => {
        getDataByType({ name: 'PAGE_FOOTER_CONFIG' }).then((res) => {
          try{
            this.pageFooter=JSON.parse(res.data.data.configValue)
          }catch (e) {
            this.pageFooter=[]
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" type="text/scss">
.login-container {
  .el-input {
    display: inline-block;
    .el-input__prefix {
      left: -30px;
    }
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      color: #333;
      padding: 0;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #333 !important;
      }
    }

    input::-webkit-input-safebox-button {
      display: none;
    }
    #sogou_secure_inputs_container {
      display: none;
    }
  }
  .el-form-item__label {
    padding: 0;
    font-size: 14px;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: #333333;
  }
  .el-form-item {
    border: none;
    border-bottom: 1px solid #dadada;
  }
  .el-button {
    height: 44px;
    // background: linear-gradient(
    //   90deg,
    //   rgba(18, 199, 188, 1) 0%,
    //   rgba(55, 213, 184, 1) 100%
    // );
    border-radius: 4px;
    border: none;
    font-size: 14px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    border: none;
  }
  .el-button.send-code-btn {
    display: inline-block;
    height: auto;
    width: auto;
    background: #fff;
    color: $mainColor;
    position: absolute;
    right: 0;
    bottom: 12px;
    font-size: 12px;
    padding: 0;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.login-container {
  @include relative;
  position: relative;
  min-height: 600px;
  .login-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .login-forget {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 4;
  }

  .login-set {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 4;
  }

  .login-banner {
    width: 100%;
    height: 86px;
    position: relative;
    z-index: 2;
    > img {
      width: 100%;
      height: 100%;
    }
  }

  .login-inner {
    width: 613px;
    position: absolute;
    z-index: 1;
    left: 50%;
    transform: translateX(-50%);
    top: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 4px 35px 0px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;
    .inner-form {
      position: relative;
      z-index: 3;
    }
    .login-form {
      width: 400px;
      margin: 0 auto;
    }
    .inner-logo {
      text-align: center;
      margin-bottom: 35px;
      width: 390px;
      height: 54px;
      .el-image {
        .image-slot {
          background-color: transparent;
        }
        img {
          display: block;
          width: 100%;
          height: 100%;
        }
      }
    }
    .inner-title {
      font-size: 28px;
      font-family: PingFang SC Semibold, PingFang SC Semibold-Semibold;
      font-weight: 600;
      text-align: center;
      color: #444444;
      margin-bottom: 130px;
    }
    .inner-txt {
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      text-align: center;
      position: absolute;
      left: 0;
      right: 0;
      bottom: -50px;
    }
  }

  .login-bottom {
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: #2e3136;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
    text-align: center;
    font-size: 12px;
    font-family: SimSun;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }

  .forget-password {
    color: $mainColor;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
  }
}
</style>
